from flask import Blueprint, request

from utilsapp import utils
from utilsapp.mysql_con import (
    db_pagelist,
    db_list,
    db_fetchone,
    db_delete,
    db_update,
    db_insert,
    db_fetchall,
)
from utilsapp.common import assign_value, parsing_data_id, get_operate
import json

bluePrint = Blueprint("algorithm", __name__)
tableName = "modelconfig"


# 分页查询
@bluePrint.route("/getlist", methods=["post"])
def table_list():
    a = request.json
    page = assign_value(a, "page")
    size = assign_value(a, "size", 20)
    device_name = assign_value(a, "device_name")
    sensor_name = assign_value(a, "sensor_name")
    modeltype = assign_value(a, "modeltype")
    sql = f"SELECT  *  from {tableName}"
    query = " where 1 = 1  "
    if device_name != "":
        query += f" and device_name like '%{device_name}%' "
    if sensor_name != "":
        query += f" and sensor_name like '%{sensor_name}%' "
    if modeltype != "":
        query += f" and modeltype like '%{modeltype}%' "
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    info = get_operate(request)
    role_id = info["role_id"]
    if scoped != "":
        query += f" and {scoped} "
    if role_id == 1 or role_id == 43:
        sql += query
    else:
        sql = sql + query + "and istest=2"

    return db_pagelist(sql, page, size)


@bluePrint.route("/add", methods=["post"])
def add():
    a = request.json
    devices = assign_value(a, "devices", [])
    istest = assign_value(a, "istest", 1)
    trouble = assign_value(a, "trouble", [])
    insert_list = []
    sql = """SELECT d.zone_id ,z.name as zone_name ,d.factory_id,f.name as factory_name,
d.company_id,d.group_id,c.name as company_name,g.name as group_name ,g.proj_no
FROM device d
left JOIN regionlevel z on z.id = d.zone_id
LEFT JOIN regionlevel f on f.id = d.factory_id
LEFT JOIN regionlevel c on c.id = d.company_id
LEFT JOIN regionlevel g on g.id = d.group_id
WHERE d.id = """
    for device in devices:
        (
            zone_id,
            zone_name,
            factory_id,
            factory_name,
            company_id,
            group_id,
            company_name,
            group_name,
            proj_no,
        ) = db_fetchall(f"{sql}{device['device_id']}")["data"][0]
        for t1 in trouble:
            t = t1[2]
            insert_list.append(
                {
                    "zone_id": zone_id,
                    "zone_name": zone_name,
                    "factory_id": factory_id,
                    "factory_name": factory_name,
                    "company_id": company_id,
                    "group_id": group_id,
                    "company_name": company_name,
                    "group_name": group_name,
                    "device_id": device["device_id"],
                    "device_name": device["device_name"],
                    "proj_no": proj_no,
                    "config": t["config"],
                    "modelcode": t["modelcode"],
                    "modeltype": t["modeltype"],
                    "trouble": t["trouble"],
                    "typecode": t["typecode"],
                    "warncode": t["warncode"],
                    "description": t["description"],
                    "status": 0,
                    "istest": istest,
                }
            )
    return db_insert(tableName, insert_list)


# 删除
@bluePrint.route("/delete", methods=["post"])
def table_delete():
    id = request.json["id"]
    return db_delete(tableName, f"WHERE id=%s", {"id": id})


@bluePrint.route("/edit", methods=["post"])
def a232():
    a = request.json
    sensor_id = assign_value(a, "sensor_id")
    channel = assign_value(a, "channel")
    config = assign_value(a, "config")
    status = assign_value(a, "status", -1)
    istest = assign_value(a, "istest")
    id_ = assign_value(a, "id")
    if status != -1:
        return db_update(tableName, {"status": status}, f"WHERE id = %s", {"id_": id_})
    sql = f"""SELECT address , port ,sensor_name,direction  from sensor
where id  = {sensor_id}"""
    address, port, sensor_name, direction = db_fetchall(sql)["data"][0]
    sensor_numid = f"{port}_{address}"
    config["data"][0]["direction_equip"] = direction
    config["data"][0]["direction_sensor"] = channel
    config["data"][0]["sensor_name"] = sensor_name
    config["data"][0]["sensor_id"] = sensor_id
    config["data"][0]["sensor_numid"] = sensor_numid
    return db_update(
        tableName,
        {
            "sensor_id": sensor_id,
            "sensor_name": sensor_name,
            "istest": istest,
            "channel": channel,
            "direction": direction,
            "sensor_numid": sensor_numid,
            "config": json.dumps(config, ensure_ascii=False),
        },
        f"WHERE id = %s",
        {"id_": id_},
    )


@bluePrint.route("/status", methods=["post"])
def status1():
    a = request.json
    id_ = assign_value(a, "id")
    status = assign_value(a, "status")
    return db_update(tableName, {"status", status}, f"WHERE id = %s", {"id_": id_})


@bluePrint.route("/threshold/line", methods=["post"])
def s12():
    a = request.json
    sensor_id = assign_value(a, "sensor_id")
    eigname = assign_value(a, "eigname")
    sql = f"SELECT * from modelconfig where sensor_id  =  {sensor_id}"

    res = db_list(sql)

    value = ""
    
    for item in res["data"]:
        # 解析一次 config
        ii = json.loads(item["config"])
        
        # 检查 data 部分
        eigkey = ii["data"][0]["data_index"]
        if eigkey == eigname:
            # 创建 config_index 到 config_value 的映射
            config_dict = {config["config_index"]: config["config_value"] for config in ii["config"]}
            
            # 获取 maxThred 的值
            value = config_dict.get("maxThred", "")
            if value:  
                if isinstance(value, list):   
                    return utils.ok(value[0])
                return utils.ok(value)
    
 
    return utils.ok(value)
